﻿/// <reference Path="../jquery-1.3.2-vsdoc.js" />
$(function () {
    var defaults = {
        space: 64,
        ismovepage: false, // 为 true 表示一次移动一屏
        element: null,
        loadimageurl: null
    };
    $.viewImage = function (options) {
        var s = $.extend(defaults, options);
        this.space = s.space;
        this.ismovepage = s.ismovepage;
        this.onimageclick = s.onimageclick;
        this.element = s.element;
        this.loadimageurl = s.loadimageurl;
    };
    $.viewImage.prototype = {
        _show: function (o) {
            $(o).css("display", "block");
        },
        _hide: function (o) {
            $(o).css("display", "none");
        },
        _eventSupported: function (eventName, el) {
            el = el || document.createElement("div");
            eventName = "on" + eventName;
            var isSupported = (eventName in el);
            if (el.setAttribute && !isSupported) {
                el.setAttribute(eventName, "return;");
                isSupported = typeof el[eventName] === "function";
            }
            el = null;
            return isSupported;
        },
        _preventDefault: function (e) { // 取消默认行为
            var event = e || window.event;
            if (event) {
                if (event.preventDefault) {
                    event.preventDefault();
                }
                else {
                    event.returnValue = false;
                }
            }
        },
        _stopPropagation: function (e) { // 停止事件冒泡
            var event = e || window.event;
            if (event) {
                if (event.stopPropagation) {
                    event.stopPropagation();
                }
                else {
                    event.cancelBubble = true;
                }
            }
        },
        _init: function () {
            var s = this;
            if (s._isCreate) {
                var b = $(document.body), w = $(window);
                s._imgnums = s.element.find("a").length;
                // 外层展示
                s._max_shadow = $("<div></div>").addClass("div_max_shadow_out").appendTo(b);
                s._max_container = $("<div></div>").addClass("div_max_container").appendTo(b);
                s._max_top = $("<div></div>").addClass("div_max_top").appendTo(s._max_container);
                s._max_move = $("<div></div>").addClass("div_max_move").appendTo(s._max_top);
                s._max_move_shadow = $("<div></div>").addClass("div_max_move_shadow").appendTo(s._max_top);
                s._max_middle = $("<div></div>").addClass("div_max_middle").css("padding", "15px 0px").appendTo(s._max_container);
                s._max_num = $("<div></div>").addClass("div_max_middle_num").appendTo(s._max_middle);
                s._max_middle_btn = $("<div></div>").addClass("div_max_middle_btn").appendTo(s._max_middle);
                s._max_close = $("<div></div>").addClass("div_max_close").appendTo(s._max_middle);
                s._max_bottom = $("<div></div>").addClass("div_max_bottom").css("padding", "10px 0px").appendTo(s._max_container);
                // 滚动
                s._container = $("<div></div>").addClass("div_max_contaioner").appendTo(s._max_bottom);
                s._leftbtn = $("<div></div>").addClass("div_max_left_btn_enabled").css("margin-right", "5px").appendTo(s._container);
                s._shadow = $("<div></div>").addClass("div_max_shadow").appendTo(s._container);
                s._rightbtn = $("<div></div>").addClass("div_max_right_btn_enabled").css("margin-left", "5px").appendTo(s._container);
                s._picture = $("<div></div>").addClass("div_max_picture").appendTo(s._shadow);
                // 图片显示层宽度
                s._picture.width(s._imgnums * s.space).html(s.element.html());
                // close
                s._close_fold = $("<a href='javascript:void(0);'>折叠</a>").appendTo(s._max_close);
                $('<span class="split"></span>').appendTo(s._max_close);
                s._close_back = $("<a href='javascript:void(0);'>关闭</a>").appendTo(s._max_close);
                // toolbar
                s._btn_prev = $('<a class="prev" title="上一张" href="javascript:void(0);"></a>').appendTo(s._max_middle_btn);
                s._btn_next = $('<a class="next" title="下一张" href="javascript:void(0);"></a>').appendTo(s._max_middle_btn);
                $('<span class="split"></span>').appendTo(s._max_middle_btn);
                s._btn_zoomin = $('<a class="zoomin" title="放大" href="javascript:void(0);"></a>').appendTo(s._max_middle_btn);
                s._btn_zoomout = $('<a class="zoomout" title="缩小" href="javascript:void(0);"></a>').appendTo(s._max_middle_btn);
                s._btn_original = $('<a class="original" title="1:1显示" href="javascript:void(0);"></a>').appendTo(s._max_middle_btn);
                s._btn_fit = $('<a class="fit" title="自适应屏幕" href="javascript:void(0);"></a>').appendTo(s._max_middle_btn);
                $('<span class="split"></span>').appendTo(s._max_middle_btn);
                s._btn_newwin = $('<a class="newwin" title="查看原图" href="" target="_blank"></a>').appendTo(s._max_middle_btn);

                s._wheel();
                s._click();
                s._toolbarClick();
            }
            // 显示
            s._show(s._max_shadow);
            s._max_container.show("fast", function () {
                s._repair(function () {
                    $("<img src='' />").attr("src", s.loadimageurl).appendTo(s._max_move);
                    s._max_move.css({
                        left: (s._max_top.width() - s._max_move.width()) / 2,
                        top: (s._max_top.height() - s._max_move.height()) / 2
                    }).show("normal", function () {
                        s._picture.find("img").eq(0).click();
                    });
                });
            });
        },
        _toolbarClick: function () {
            var s = this;
            s._btn_prev.click(function () {
                s._isFirst();
                s._picture.find("img").eq(s._currentIndex == 0 ? 0 : s._currentIndex - 1).click();
            });
            s._btn_next.click(function () {
                s._isFirst();
                s._picture.find("img").eq(s._currentIndex == s._imgnums - 1 ? s._currentIndex : s._currentIndex + 1).click();
            });
            s._btn_zoomin.click(function () {
                s._resize(1.2);
            });
            s._btn_zoomout.click(function () {
                s._resize(0.8);
            });
            s._btn_original.click(function () {
                var src = s._picture.find("img.current").parent().attr("href");
                s._max_move.empty();
                $("<img src='' />").attr("src", src).appendTo(s._max_move);
                s._calcPosition();
                s._navigator();
            });
            s._btn_fit.click(function () {
                var src = s._picture.find("img.current").parent().attr("href");
                s._max_move.empty();
                var img = $("<img src='' />").attr("src", src).appendTo(s._max_move);
                s._repairSize(img);
                s._calcPosition();
                s._navigator();
            });
        },
        _repair: function (func) { // 调整高度和宽度
            var s = this, b = $(document.body), w = $(window), h = s._picture.height();
            s._max_shadow.height(b.height()).width(b.width());
            s._max_container.height(w.height()).width(w.width());
            s._leftbtn.height(h);
            s._rightbtn.height(h);
            // 移动距离和显示数量
            s._shownum = Math.floor((w.width() - (s._leftbtn.width() + s._rightbtn.width() + 5 * 2)) / s.space);
            s._shownum = s._shownum < s._imgnums ? s._shownum : s._imgnums;
            s._movespace = s.ismovepage ? s.space * s._shownum : s.space;

            s._shadow.height(h).width(s._shownum * s.space);
            s._container.width(s._leftbtn.width() + s._rightbtn.width() + s._shadow.width() + 5 * 2);
            // toolbar 宽度
            var l = s._max_middle.width() - s._max_num.width() - s._max_close.width() - s._max_middle_btn.width();
            s._max_middle_btn.css("margin-left", l <= 0 ? 0 : Math.floor(l / 2));

            var botheight = s._max_bottom.is(":hidden") ? 0 : s._max_bottom.height() + 10 * 2;
            var topheight = s._max_container.height() - (s._max_middle.height() + 15 * 2 + botheight);
            s._max_top.animate({ "height": topheight }, "normal", function () {
                if (func && $.isFunction(func)) { func(); }
                s._repairSize(s._max_move.find("img"));
                s._calcPosition();
                s._navigator();
                s._move();
            });
        },
        _repairSize: function (img) { // 调整图片大小到合适的位置
            var s = this, toph = s._max_top.height(), topw = s._max_top.width();
            var ih = img.height(), iw = img.width();
            var sh = toph / ih, sw = topw / iw, scale = (sh > sw ? sw : sh) - 0.05;
            if (ih - toph > 0 || iw - topw > 0) {
                img.height(ih * scale).width(iw * scale);
            }
        },
        _calcPosition: function () { // 计算图片位置
            var s = this;
            var moveh = s._max_move.height(), toph = s._max_top.height();
            var movew = s._max_move.width(), topw = s._max_top.width();
            var left = (topw - movew) / 2, top = (toph - moveh) / 2;
            s._max_move.css({ left: left, top: top });
            s._max_move_shadow.height(moveh).width(movew).css({ left: left, top: top }).empty();
        },
        _navigator: function () {
            var s = this, moveh = s._max_move.height(), movew = s._max_move.width();
            if (s._max_top.width() >= movew && s._max_top.height() >= moveh) {
                // 取消移动
                s._unMouse();
                // 添加 上一张 和 下一张 操作               
                var isf = s._isFirst(), isl = s._isLast();
                var preva = $("<a href='javascript:void(0);'></a>").appendTo(s._max_move_shadow);
                preva.attr({ "class": (isf ? "none" : "p"), "title": (isf ? "" : "上一张") });
                preva.height(moveh).width(Math.floor(movew / 2)).click(function () {
                    if (!isf) {
                        s._picture.find("img").eq(--s._currentIndex).click();
                    }
                });
                var nexta = $("<a href='javascript:void(0);'></a>").appendTo(s._max_move_shadow);
                nexta.attr({ "class": (isl ? "none" : "n"), "title": (isl ? "" : "下一张") });
                nexta.height(moveh).width(Math.floor(movew / 2)).click(function () {
                    if (!isl) {
                        s._picture.find("img").eq(++s._currentIndex).click();
                    }
                });
            } else {
                s._mouse();
            }
        },
        _wheel: function () { // 滚轮事件
            var s = this, wheel = function (e) {
                var dis, direct = 0, evt = e || window.event, w = h = 0;
                if (evt.wheelDelta) {
                    direct = evt.wheelDelta > 0 ? 1 : -1;
                } else if (evt.detail) {
                    direct = evt.detail < 0 ? 1 : -1;
                }
                s._resize(direct == -1 ? 0.95 : 1.05);
                s._preventDefault(e);
            };
            s._max_move.bind(s._eventSupported("mousewheel") ? "mousewheel" : "DOMMouseScroll", wheel);
            s._max_move_shadow.bind(s._eventSupported("mousewheel") ? "mousewheel" : "DOMMouseScroll", wheel);
        },
        _resize: function (dis) {
            var s = this;
            var w = Math.floor(s._max_move.width() * dis);
            var h = Math.floor(s._max_move.height() * dis);
            s._max_move.find("img").width(w).height(h);
            s._calcPosition();
            s._navigator();
        },
        _isFirst: function () { // 是否最前一张图
            var imgs = this._picture.find("img"), curimg = this._picture.find("img.current");
            this._currentIndex = imgs.index(curimg);
            return this._currentIndex == 0;
        },
        _isLast: function () { // 是否最后一张图
            var imgs = this._picture.find("img"), curimg = this._picture.find("img.current");
            this._currentIndex = imgs.index(curimg);
            return this._currentIndex == imgs.length - 1;
        },
        _click: function () {
            var s = this;
            var mouseover = function () {
                $(this).addClass("current").siblings("img[class!='current']").removeClass("current");
            };
            var mouseout = function () {
                $(this).removeClass("current");
            };
            var click = function (e) {
                var src = $(this).parent().attr("href");
                s._picture.find("img.current").removeClass("current").bind("mouseover", mouseover).bind("mouseout", mouseout);
                $(this).addClass("current").unbind("mouseover").unbind("mouseout");

                s._isFirst();
                s._max_num.text(s._imgnums + ' 张 第 ' + (s._currentIndex + 1) + ' 张');
                s._btn_newwin.attr("href", src);
                var pleft = parseInt(s._picture.css("left")), curleft = (s._currentIndex + 1) * s.space;
                if (Math.abs(pleft) >= curleft && pleft < 0) {
                    s._leftbtn.click();
                } else if (curleft - Math.abs(pleft) > s._shadow.width()) {
                    s._rightbtn.click();
                }

                s._max_move.empty();
                var evname = s._eventSupported("readystatechange") ? "readystatechange" : "load";
                var img = $("<img src='' />").attr("src", s.loadimageurl).appendTo(s._max_move);
                var imgload = function () {
                    if (img.attr("complete") || img.attr("readyState") == "complete") {
                        s._repairSize(img);
                        s._calcPosition();
                        s._navigator();
                    }
                };
                img.attr("src", src).bind(evname, imgload);
                imgload();
                return false;
            };
            s._picture.find("img").bind("mouseover", mouseover).bind("mouseout", mouseout).click(click);
            s._close_fold.click(function () {
                s._max_bottom.toggle();
                s._repair();
            });
            s._close_back.click(function () {
                s._max_move.empty();
                s._max_top.height(0);
                s._hide(s._max_shadow);
                s._hide(s._max_container);
            });
        },
        _move: function () {
            var s = this;
            var leftclick = function () {
                f_ld();
                var l = parseInt(s._picture.css("left"));
                s._picture.animate({ "left": l + s._movespace }, 'fast', null, function () {
                    f_le();
                    l = parseInt(s._picture.css("left"));
                    if (s._picture.width() - Math.abs(l) > s._shadow.width()) {
                        f_re();
                    }
                    if (l >= 0) {
                        f_ld();
                    }
                });
            };
            var rightclick = function () {
                f_rd();
                var l = parseInt(s._picture.css("left"));
                s._picture.animate({ "left": l - s._movespace }, 'fast', null, function () {
                    f_re();
                    l = parseInt(s._picture.css("left"));
                    if (s._picture.width() - Math.abs(l) <= s._shadow.width()) {
                        f_rd();
                    }
                    if (l < 0) {
                        f_le();
                    }
                });
            };
            var f_ld = function () { s._leftbtn.addClass("div_max_left_btn_disabled").unbind("click"); }
            var f_rd = function () { s._rightbtn.addClass("div_max_right_btn_disabled").unbind("click"); }
            var f_le = function () { s._leftbtn.removeClass("div_max_left_btn_disabled").bind("click", leftclick); }
            var f_re = function () { s._rightbtn.removeClass("div_max_right_btn_disabled").bind("click", rightclick); }
            s._leftbtn.unbind("click").click(leftclick);
            s._rightbtn.unbind("click").click(rightclick);

            s._isFirst();
            var hidenum = Math.floor(Math.abs(parseInt(s._picture.css("left"))) / s.space);
            var currnum = s._imgnums - hidenum;
            var remainnum = s._shownum - currnum;

            if (hidenum == 0) {
                f_ld();
            } else {
                f_le();
            }
            if (remainnum >= 0) {
                f_rd();
                var l = parseInt(s._picture.css("left"));
                s._picture.animate({ "left": l + (hidenum > remainnum ? remainnum : hidenum) * s.space }, 'fast');
            } else {
                if (s._currentIndex - hidenum + 1 > s._shownum) {
                    s._picture.animate({ "left": -s._currentIndex * s.space }, 'fast');
                }
                f_re();
            }
        },
        _mouse: function () { // 拖动
            var s = this, d = $(document), data = {};
            s._max_move_shadow.mousedown(function (e) {
                var moving = false, evt = e.originalEvent, of = s._max_move_shadow.offset();
                if ($.browser.msie && (evt.button == 1 || evt.button == 0)) {
                    moving = true;
                } else if (evt.button == 0) {
                    moving = true;
                }
                data = {
                    IsMove: moving,
                    x: d.scrollTop() + evt.clientY - of.top,
                    y: d.scrollLeft() + evt.clientX - of.left
                };
            });
            d.mouseup(function (e) {
                data = { IsMove: false, x: 0, y: 0 };
            }).mousemove(function (e) {
                var evt = e.originalEvent;
                if (data.IsMove && (evt.button == 1 || evt.button == 0)) {
                    var pos = { top: evt.clientY - data.x, left: evt.clientX - data.y };
                    s._max_move.css(pos);
                    s._max_move_shadow.css(pos);
                }
            });
        },
        _unMouse: function () { // 取消拖动
            this._max_move_shadow.unbind("mousedown");
            $(document).unbind("mouseup").unbind("mousemove");
        },
        apply: function (flag) {
            var s = this, b = $(document.body), w = $(window);
            s._isCreate = flag;
            s._init();
            if (flag) {
                w.bind("resize", function () {
                    s._repair();
                }).bind("scroll", function () {
                    s._max_container.css("top", $(this).scrollTop());
                }).scroll();
            }
        }
    };

    $.fn.ViewImage = function (options) {
        var vi = $(document.body).data("vi_" + $(this).attr("id"));
        if (vi == undefined) {
            vi = new $.viewImage($.extend({ element: $(this) }, options));
            $(document.body).data("vi_" + $(this).attr("id"), vi);
            vi.apply(true);
        } else {
            vi.apply(false);
        }
    };
});